﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;

namespace DCT.Huiteng.Utility.Cache
{
    public class KeyValueCache<TValue>
    {
        private ConcurrentDictionary<string, TValue> cache;

        public KeyValueCache()
        {
            this.cache = new ConcurrentDictionary<string, TValue>();
        }

        public void Reset()
        {
            if (this.cache.Count > 0)
            {
                this.cache.Clear();
            }
        }

        public TValue GetValue(string key, Func<string, TValue> getHandler)
        {
            TValue result = default(TValue);
            result = this.cache.GetOrAdd(key,getHandler);
            return result;
        }

        public void Remove(string key) {
            TValue tmp;
            this.cache.TryRemove(key, out tmp);
        }
    }
}
